import 'package:cloud_medicine/components/address_list.dart';
import 'package:cloud_medicine/components/order_row.dart';
import 'package:cloud_medicine/http/address_api.dart';
import 'package:cloud_medicine/http/config.dart';
import 'package:cloud_medicine/http/shop_api.dart';
import 'package:cloud_medicine/model/user_address.dart';
import 'package:cloud_medicine/pages/order_list.dart';
import 'package:flutter/material.dart';

class CurrentOrder extends StatefulWidget {
  final String shopname;
  final num deliveryFee;
  final num allprice;
  final num shopID;
  final ValueChanged clearCart;
  final List<Map<String, dynamic>> cartList;
  CurrentOrder(
      {Key key,
      @required this.shopID,
      @required this.shopname,
      @required this.deliveryFee,
      @required this.allprice,
      @required this.cartList,
      this.clearCart})
      : super(key: key);
  @override
  _CurrentOrderState createState() => _CurrentOrderState();
}

class _CurrentOrderState extends State<CurrentOrder> {
  String address;
  List<AddressItem> addressList = [];
  String name;
  num phone;
  int _value = -1;
  bool _loading = false;

  Future<Null> _init() async {
    setState(() {
      _loading = true;
    });

    dynamic res = await getAddressList_api('$backIP/address/list'); //接口路径
    res['data'].forEach((dynamic addressItem) {
      //遍历接口中的数据
      AddressItem addressItemModel = AddressItem.init(addressItem);
      addressList.add(addressItemModel);
    });
    if (mounted) {
      setState(() {
        _loading = false;
      });
    }
    return;
  }

  Future _commitOrder() async {
    List<Map<String, num>> medicineNumber = [];
    for (int i = 0; i < widget.cartList.length; i++) {
      medicineNumber.add({
        'medicineid': widget.cartList[i]['id'],
        'number': widget.cartList[i]['number'] //传给后端的数组字段，检查名字是否一样
      });
    }
    print('~~~~~~');
    print(name);
    print(address);
    print(phone);
    print(widget.deliveryFee);
    print(widget.allprice);
    print(medicineNumber);
    await createOrder_api('$backIP/shop/createOrder', {
      'shopID': widget.shopID,
      'name': name,
      'address': address,
      'phonenumber': phone,
      'delivery_fee': widget.deliveryFee,
      'allprice': widget.allprice,
      'medicineID': medicineNumber
    });
  }

  _childLayout() {
    if (_loading) {
      return Center(
        child: Container(
          child: CircularProgressIndicator(),
        ),
      );
    } else {
      print('~~~~~~~~~~~~');
      print(widget.cartList);
      return ListView(
        children: [
          GestureDetector(
            onTap: () {
              showModalBottomSheet(
                  context: context,
                  builder: (context) {
                    return Container(
                      child: SingleChildScrollView(
                        child: Container(
                          margin: EdgeInsets.all(15),
                          height: 60 * addressList.length.toDouble() + 80,
                          child: Column(
                            children: [
                              Container(
                                margin: EdgeInsets.only(bottom: 5),
                                child: Text('选择收货地址'),
                              ),
                              Divider(
                                thickness: 1,
                                color: Colors.grey[200],
                              ),
                              AddressList(
                                addressList: addressList,
                                callback: (value) {
                                  setState(() {
                                    _value = value;
                                  });
                                },
                              ),
                              AddAddress(),
                            ],
                          ),
                        ),
                      ),
                    );
                  });
            },
            child: Card(
              elevation: 5,
              child: Container(
                  margin: EdgeInsets.all(10),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Container(
                              margin: EdgeInsets.only(bottom: 5),
                              child: _showAddress())
                        ],
                      ),
                      Icon(Icons.chevron_right)
                    ],
                  )),
            ),
          ),
          Card(
            elevation: 5,
            child: Container(
              margin: EdgeInsets.all(10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    child: Text(
                      widget.shopname,
                      style: TextStyle(fontSize: 17),
                    ),
                  ),
                  Divider(
                    thickness: 1,
                    color: Colors.grey[200],
                  ),
                  MedicineItemList(
                    deliveryFee: widget.deliveryFee,
                    price: widget.allprice,
                    cartList: widget.cartList,
                  )
                ],
              ),
            ),
          ),
        ],
      );
    }
  }

  _showAddress() {
    print(_value);
    if (_value == -1) {
      //刚进入此页面，显示默认地址
      return Column(
        children: addressList.map((e) {
          if (e.isMain) {
            address = e.address;
            name = e.name;
            phone = num.parse(e.phone);
            return Column(
              children: [
                Text(
                  e.address,
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
                ),
                Text('${e.name} ${e.phone}')
              ],
            );
          } else {
            return Container();
          }
        }).toList(),
      );
    } else {
      //选择地址之后，显示被选择的地址
      address = addressList[_value].address;
      name = addressList[_value].name;
      phone = num.parse(addressList[_value].phone);
      return Column(
        children: [
          Text(addressList[_value].address,
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600)),
          Text('${addressList[_value].name} ${addressList[_value].phone}')
        ],
      );
    }
  }

  @override
  void initState() {
    super.initState();
    _init();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[300],
      appBar: AppBar(
        centerTitle: true,
        title: Text('提交订单'),
      ),
      body: _childLayout(),
      floatingActionButton: Padding(
        padding: EdgeInsets.only(right: 10),
        child: Card(
          color: Colors.black,
          margin: EdgeInsets.only(top: 10),
          child: SizedBox(
            height: 40,
            width: MediaQuery.of(context).size.width - 70,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(left: 10),
                  child: Text(
                    '￥${widget.allprice}',
                    style: TextStyle(color: Colors.white, fontSize: 18),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(right: 5),
                  width: 70,
                  child: RaisedButton(
                    color: Colors.yellow[700],
                    shape: StadiumBorder(),
                    child: Text(
                      '提交',
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.w500),
                    ),
                    onPressed: () {
                      //TODO:传给后端
                      _commitOrder();
                      widget.clearCart(widget.shopID);
                      Navigator.pop(context);
                      Navigator.of(context).push(
                        MaterialPageRoute(builder: (context) => OrderList()),
                        // (route) => route == null
                      );
                    },
                  ),
                )
              ],
            ),
          ),
          shape: StadiumBorder(),
        ),
      ),
    );
  }
}
